<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <style type="text/css">
        .layui-form-item {
            margin-top: 30px;
        }

        .layui-form-item input {
            width: 300px;
        }

        .layui-form-label {
            width: 100px;
        }
    </style>
</head>
<body>

<!-- 菜单栏  搜索框 -->
<div class="layui-form">
    <blockquote class="layui-elem-quote quoteBox">
        <shiro:hasPermission name="crm:dept:list">
            <!-- 部门名称 -->
            <label class="layui-label">部门名称</label>
            <div style="width: 150px;" class="layui-inline">
                <input type="text" id="dept_name" name="dept_name" placeholder="部门名称"
                       style="width: 100%;" class="layui-input">
            </div>
            <div class="layui-inline">
                <button class="layui-btn" type="button" id="searchBtn"><i class="layui-icon">&#xe615;</i>搜索</button>
            </div>
        </shiro:hasPermission>
        <!-- 添加按钮 -->
        <shiro:hasPermission name="crm:dept:add">
            <div class="layui-inline">
                <!--
                <button type="button" class="layui-btn layui-btn-warm" id="addButton">
                    <i class="layui-icon">&#xe608;</i> 添加部门
                </button>
                -->
                <button type="button" class="layui-btn layui-btn-primary expandAllBtn">
                    <i class="layui-icon layui-icon-add-circle"></i> 展开/折叠
                </button>
            </div>
        </shiro:hasPermission>
    </blockquote>
</div>

<!-- 添加部门框 -->
<div id="addDept" class="layui-hide">
    <form class="layui-form addDept" action="" style="padding:10px" lay-filter="addDept">
        <div class="layui-form-item">
            <label class="layui-form-label">上级部门</label>
            <div class="layui-input-inline">
                <input type="hidden" name="parentId"/>
                <input type="text" name="parentName" value="" class="layui-input" readonly>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">部门名称</label>
            <div class="layui-input-inline">
                <input type="hidden" name="deptId"/>
                <input type="text" name="deptName" required lay-verify="required" placeholder="请输入部门名称"
                       autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">显示顺序</label>
            <div class="layui-input-inline">
                <input type="text" name="orderNum" placeholder="请输入显示序号" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">部门主管</label>
            <div class="layui-input-inline">
                <input type="text" name="leader" placeholder="请输入部门主管" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">联系电话</label>
            <div class="layui-input-inline">
                <input type="text" name="phone" placeholder="请输入联系电话" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">邮箱</label>
            <div class="layui-input-inline">
                <input type="text" name="email" placeholder="请输入部门邮箱" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">部门状态</label>
            <div class="layui-input-inline">
                <input type="radio" name="status" class="layui-input" title="正常" value="0" checked/>
                <input type="radio" name="status" class="layui-input" title="禁用" value="1"/>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="addDept">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>
<!-- 添加部门框 -->

<!-- 编辑部门框 -->
<div id="updateDeptDialog" class="layui-hide">
    <form class="layui-form updateDeptDialog" action="" style="padding:10px" lay-filter="updateDeptDialog">
        <input type="hidden" name="id" value=""/>
        <div class="layui-form-item">
            <label class="layui-form-label">上级部门</label>
            <div class="layui-input-inline">
                <input type="hidden" name="parentId"/>
                <input type="text" name="parentName" value="" class="layui-input" readonly>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">部门名称</label>
            <div class="layui-input-inline">
                <input type="hidden" name="deptId"/>
                <input type="text" name="deptName" required lay-verify="required" placeholder="请输入部门名称"
                       autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">显示顺序</label>
            <div class="layui-input-inline">
                <input type="text" name="orderNum" placeholder="请输入显示序号" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">部门主管</label>
            <div class="layui-input-inline">
                <input type="text" name="leader" placeholder="请输入部门主管" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">联系电话</label>
            <div class="layui-input-inline">
                <input type="text" name="phone" placeholder="请输入联系电话" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">邮箱</label>
            <div class="layui-input-inline">
                <input type="text" name="email" placeholder="请输入部门邮箱" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">部门状态</label>
            <div class="layui-input-inline">
                <input type="radio" name="status" class="layui-input" title="正常" value="0" checked/>
                <input type="radio" name="status" class="layui-input" title="禁用" value="1"/>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="updateDeptDialog">立即提交</button>
            </div>
        </div>
    </form>
</div>
<!-- 编辑部门框 -->

<table class="layui-table layui-form" id="tree-table"></table>

<script type="text/javascript">

    layui.config({
        base: '../../js/',
    }).use(['treeTable', 'layer', 'code', 'form'], function () {
        var $ = layui.$;
        var form = layui.form;
        var layer = layui.layer;
        var treeTable = layui.treeTable;

        var re;

        init();

        function init() {
            $.ajax({
                url: '${pageContext.request.contextPath}/dept/list',
                data: {},
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    initTable(data);
                }
            });
        }

        function initTable(data) {
            re = treeTable.render({
                elem: '#tree-table',
                data: data,
                icon_key: 'deptName',
                is_checkbox: false,
                primary_key: "deptId",
                parent_key: "parentId",
                top_value: 0,
                end: function (e) {
                    form.render();
                },
                cols: [
                    {
                        key: 'deptId',
                        title: '部门编号',
                        width: '10%',
                        align: 'center',
                    },
                    {
                        key: 'deptName',
                        title: '部门名称',
                        width: '30%'
                    },
                    {
                        key: 'orderNum',
                        title: '显示顺序',
                        width: '10%',
                        align: 'center',
                    },
                    {
                        key: 'leader',
                        title: '部门领导',
                        width: '10%',
                        align: 'center',
                    },
                    {
                        title: '开关',
                        width: '10%',
                        align: 'center',
                        template: function (item) {
                            if (item.status == 0)
                                return '<input type="checkbox" name="close" lay-skin="switch" lay-text="正常|禁用" checked>';
                            else
                                return '<input type="checkbox" name="close" lay-skin="switch" lay-text="正常|禁用">';
                        }
                    },
                    {
                        title: '操作',
                        align: 'center',
                        width: "15%",
                        template: function (item) {
                            var html = '<shiro:hasPermission name="crm:dept:edit">\n' +
                                '        <a class="layui-btn layui-btn-warm layui-btn-xs" lay-filter="add">添加子部门</a>\n' +
                                '    </shiro:hasPermission>\n' +
                                '<shiro:hasPermission name="crm:dept:edit">\n' +
                                '        <a class="layui-btn layui-btn-xs" lay-filter="edit">编辑</a>\n' +
                                '    </shiro:hasPermission>\n' +
                                '    <shiro:hasPermission name="crm:dept:remove">\n' +
                                '        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-filter="del">删除</a>\n' +
                                '    </shiro:hasPermission>';
                            return html;
                        }
                    }
                ]
            });
            form.render('radio')
            // 监听展开关闭
            treeTable.on('tree(flex)', function (data) {
                // layer.msg(JSON.stringify(data));
            })
            // 监听自定义：新增
            treeTable.on('tree(add)', function (data) {
                addChildDept(data.item);
            });
            // 监听自定义：编辑更新
            treeTable.on('tree(edit)', function (data) {
                editDept(data.item);
            });
            // 监听自定义：删除操作
            treeTable.on('tree(del)', function (data) {
                //删除
                layer.confirm("确定要删除这个部门吗？", function (index) {
                    deleteDept(data.item);
                    layer.close(index);
                });
            });
            // 获取选中值，返回值是一个数组（定义的primary_key参数集合）
            $('.get-checked').click(function () {
                // layer.msg('选中参数' + treeTable.checked(re).join(','))
            })

            // tree表格树 展开/折叠
            var expandFlag = false;
            $('.expandAllBtn').click(function () {
                if (expandFlag) {
                    treeTable.openAll(re);
                } else {
                    treeTable.closeAll(re);
                }
                expandFlag = expandFlag ? false : true;
            })


            //搜索功能
            $('#searchBtn').on('click', function () {
                var deptName = $("#dept_name").val();
                $.ajax({
                    url: '${pageContext.request.contextPath}/dept/list',
                    data: {
                        deptName: deptName
                    },
                    type: 'post',
                    dataType: 'json',
                    success: function (data) {
                        var parentId = data[0].parentId;
                        re.top_value = parentId;
                        re.data = data;
                        treeTable.render(re);
                    }
                });
            });
        }

        /**
         * 添加部门  打开弹出框
         */
        function addChildDept(data) {
            //打开页面层
            var html = "";
            layer.open({
                type: 1,
                title: "新增部门",
                content: $('#addDept').html(),
                area: '500px',
                success: function (layero, index) {
                    html = $('#addDept').html();
                    $('#addDept').html("");
                    layui.form.render(null, 'addDept');
                    $("[name=parentId]").val(data.deptId);
                    $("[name=parentName]").val(data.deptName);
                },
                cancel: function (index, layero) {
                    $('#addDept').html(html);
                },
                end: function () {
                    $('#addDept').html(html);
                }
            })
        }

        //添加部门表单提交
        layui.form.on("submit(addDept)", function (data) {
            // console.log(data); //被执行事件的元素DOM对象，一般为button对象
            //1. 提交数据
            $.ajax({
                url: "${pageContext.request.contextPath}/dept/save",
                type: "post",
                data: data.field,
                dataType: "json",
                beforeSend: function () {
                    loading = layer.load();
                },
                success: function (data) {
                    if (data != null) {
                        if (data.code == 0) {
                            //2. 关闭添加窗口
                            layer.closeAll();
                            //3. 重新加载表格数据
                            init();
                            //4. 提示信息
                            layer.msg("添加成功!");

                        } else {
                            layer.msg(data.msg);
                        }
                    }
                },
                error: function () {
                    layer.msg("服务器开小差了!");
                },
                complete: function () {
                    layer.close(loading);
                }
            });

            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        /**
         * 添加部门  打开弹出框
         */
        function editDept(data) {
            if (data.parentId != 0) {
                $.ajax({
                    url: '${pageContext.request.contextPath}/dept/getDept',
                    data: {deptId: data.parentId},
                    type: 'post',
                    dataType: 'json',
                    async: false,
                    success: function (res) {
                        if (res.success) {
                            data.parentName = res.data ? res.data.deptName : "顶级部门无父级部门";
                        }
                    },
                    error: function (res) {
                        layer.msg(res.msg);
                    }
                });
            } else {
                data.parentName = "顶级部门无父级部门";
            }

            //打开页面层
            var html = "";
            layer.open({
                type: 1,
                title: "编辑部门",
                content: $('#updateDeptDialog').html(),
                area: '500px',
                success: function (layero, index) {
                    html = $('#updateDeptDialog').html();
                    $('#updateDeptDialog').html("");
                    layui.form.render(null, 'updateDeptDialog');
                },
                cancel: function (index, layero) {
                    $('#updateDeptDialog').html(html);
                },
                end: function () {
                    $('#updateDeptDialog').html(html);
                }
            });

            //设置值
            form.val('updateDeptDialog', {
                "deptId": data.deptId,
                "deptName": data.deptName,
                "parentId": data.parentId,
                "parentName": data.parentName,
                "orderNum": data.orderNum,
                "leader": data.leader,
                "phone": data.phone,
                "email": data.email,
                "status": data.status,
                "remarks": data.remarks,
                "categoryId": data.categoryId
            });
        }

        //更新部门表单提交
        layui.form.on("submit(updateDeptDialog)", function (data) {
            console.log(data.elem); //被执行事件的元素DOM对象，一般为button对象
            console.log(data.form); //被执行提交的form对象，一般在存在form标签时才会返回
            console.log(data.field); //当前容器的全部表单字段，名值对形式：{name: value}

            //1. 提交数据
            $.ajax({
                url: "${pageContext.request.contextPath}/dept/update",
                type: "post",
                data: data.field,
                dataType: "json",
                beforeSend: function () {
                    loading = layer.load();
                },
                success: function (data) {
                    if (data != null) {
                        if (data.code == 0) {

                            //2. 关闭添加窗口
                            layer.closeAll();

                            //3. 重新加载表格数据
                            console.log("更新后执行init()");
                            init();

                            //4. 提示信息
                            layer.msg("更新成功!");

                        } else {
                            layer.msg(data.msg);
                        }
                    }
                },
                error: function () {
                    layer.msg("服务器开小差了!");
                },
                complete: function () {
                    layer.close(loading);
                }
            });

            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        function deleteDept(data) {
            $.ajax({
                url: "${pageContext.request.contextPath}/dept/remove",
                type: "post",
                data: {
                    "deptId": data.deptId,
                },
                dataType: "json",
                beforeSend: function () {
                    loading = layer.load();
                },
                success: function (res) {
                    if (res.code == 0) {
                        layer.msg("删除成功!");
                        console.log("删除后执行init()");
                        init();
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function () {
                    layer.msg("服务器开小差了!");
                },
                complete: function () {
                    layer.close(loading);
                }
            })
        }
    });

</script>
</body>
</html>
